﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using NPOI.HSSF.UserModel;
using System.IO;

namespace HermesWinForm
{
    public partial class SynchronizationOrderInfo : Form
    {
        Thread threadImport;

        List<HermesWinForm.OrdersServiceReference.UnSyncOrderInfo> ErrList;

        public SynchronizationOrderInfo()
        {
            InitializeComponent();
        }

        private void SynchronizationOrderInfo_Load(object sender, EventArgs e)
        {
            string[] carrierNames = CarrierInfo.GetCarrierNames();
            for (int i = 0; i < carrierNames.Length; ++i)
            {
                cbCarriers.Items.Insert(i, carrierNames[i]);
            }

            this.btnSync.Enabled = false;
        }

        private void cbCarriers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCarriers.SelectedItem.ToString() != "")
            {
                btnSync.Enabled = true;
            }
            else
            {
                btnSync.Enabled = false;
            }
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            ErrList = new List<OrdersServiceReference.UnSyncOrderInfo>();
            string message = string.Empty;

            if (cbCarriers.SelectedItem.ToString() == "")
            {
                MessageBox.Show("Please select ther carrier.");
            }

            OrdersServiceReference.SalesOrderSoapClient orderClient = new OrdersServiceReference.SalesOrderSoapClient();
            HermesWinForm.OrdersServiceReference.UnSyncOrderInfo[] unSyncOrderInfos 
                = orderClient.GetUnSyncOrders(CarrierInfo.GetCarrierID(cbCarriers.SelectedItem.ToString()));

            richtxtMessage.Text = "共有" + unSyncOrderInfos.Length + "单需要与" + cbCarriers.SelectedItem.ToString() + "同步信息";

            threadImport = new Thread(delegate()
            {
                int i = 1;
                foreach (HermesWinForm.OrdersServiceReference.UnSyncOrderInfo temp in unSyncOrderInfos)
                {
                    StringBuilder sbMessage = new StringBuilder();
                    if (this.InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(delegate()
                        {
                            sbMessage.AppendLine("---------------------------");
                            sbMessage.AppendLine("正在同步第" + i + "条数据：");
                        }));
                    }
                    try
                    {
                        if (CarrierInfo.GetCarrierID(cbCarriers.SelectedItem.ToString())==1)
                        {
                            message = orderClient.SyncEUBOrder(temp);
                        }
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                if (message == "0")
                                    message = "同步成功!";
                                else
                                {
                                    temp.Notes = message;
                                    ErrList.Add(temp);
                                }
                                sbMessage.AppendLine("处理结果：" + message);
                                richtxtMessage.AppendText(sbMessage.ToString());
                            }));
                        }
                    }
                    catch (System.Exception ex)
                    {
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                temp.Notes = message;
                                ErrList.Add(temp);
                                sbMessage.AppendLine("处理结果：" + ex.Message);
                                richtxtMessage.AppendText(sbMessage.ToString());
                            }));
                        }
                    }

                    i++;
                }

                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        StringBuilder sbMessage = new StringBuilder();
                        sbMessage.AppendLine("---------------------------");
                        sbMessage.AppendLine(string.Format("全部处理完成，总共处理{0}条数据，{1}条数据同步成功，{2}条数据同步失败。", unSyncOrderInfos.Length, unSyncOrderInfos.Length - ErrList.Count, ErrList.Count));
                        richtxtMessage.AppendText(sbMessage.ToString());

                        
                        if (ErrList.Count > 0)
                        {
                            btnExportErrorOrders.Visible = true;
                        }
                    }));
                }
            });

            threadImport.Start();
        
        }

        private void btnExportErrorOrders_Click(object sender, EventArgs e)
        {
            DialogResult result = saveOrdersFile.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                ExportErrorOrders(saveOrdersFile.FileName);
            }
            else
            {
                MessageBox.Show("选择的保存文件失败。");
            }
        }


        private void ExportErrorOrders(string fileName)
        {
            //创建xls文件
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建sheet表单，默认名称为sheet1
            HSSFSheet sheet = workbook.CreateSheet("Fail to Sync Data");


            //创建行，并设定第一行的表头
            HSSFRow rowTitle = sheet.CreateRow(0);

            rowTitle.CreateCell(0, HSSFCellType.STRING).SetCellValue("OrderID");
            rowTitle.CreateCell(1, HSSFCellType.STRING).SetCellValue("OrderNumber");
            rowTitle.CreateCell(2, HSSFCellType.STRING).SetCellValue("SiteID");
            rowTitle.CreateCell(3, HSSFCellType.STRING).SetCellValue("Fail Reason");


            int rowNum = 0;
            foreach (HermesWinForm.OrdersServiceReference.UnSyncOrderInfo temp in ErrList)
            {
                HSSFRow rowContent = sheet.CreateRow(rowNum + 1);//创建内容行

                //对第1行对应的单元格分别设定单元格内容属性和填充对应的值
                rowContent.CreateCell(0, HSSFCellType.STRING).SetCellValue(temp.OrderID);
                rowContent.CreateCell(1, HSSFCellType.STRING).SetCellValue(temp.Ordernumber);
                rowContent.CreateCell(2, HSSFCellType.STRING).SetCellValue(temp.SiteID);
                rowContent.CreateCell(3, HSSFCellType.STRING).SetCellValue(temp.Notes);
                rowNum++;//动态增加行号
            }

            //写入excel文件
            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(fs);//把流写入文件
            }

            MessageBox.Show(rowNum - 1 + "Item to Export");//实际导出的数据比定义的行号少1            
        }


    }
}
